/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import ohos.app.Context;
import ohos.bundle.BundleInfo;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import io.sentry.ILogger;
import io.sentry.SentryLevel;

/**
 * ContextUtils
 *
 * @since 2021-06-01
 */
public final class ContextUtils {
    private ContextUtils() {
    }

    /**
     * Return the Application's PackageInfo if possible, or null.
     *
     * @param context Context
     * @param logger ILogger
     * @return the Application's PackageInfo if possible, or null
     */
    @Nullable
    public static BundleInfo getPackageInfo(final @NotNull Context context, final @NotNull ILogger logger) {
        try {
            return context.getBundleManager().getBundleInfo(context.getBundleName(), 0);
        } catch (Exception e) {
            logger.log(SentryLevel.ERROR, "Error getting package info.", e);
            return null;
        }
    }

    /**
     * Returns the App's version code based on the PackageInfo
     *
     * @param bundleInfo the BundleInfo class
     * @return the versionCode or LongVersionCode based on your API version
     */
    @NotNull
    public static String getVersionCode(final @NotNull BundleInfo bundleInfo) {
        return getVersionCodeDep(bundleInfo);
    }

    @SuppressWarnings("deprecation")
    private static @NotNull String getVersionCodeDep(final @NotNull BundleInfo bundleInfo) {
        return Integer.toString(bundleInfo.getVersionCode());
    }
}
